﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using Rison.BusinessFacade.Common;
using Rison.DataAccess.Data.Biz;
using Rison.DataAccess.Common;
using Rison.BusinessFacade.Helper;
using Rison.BusinessFacade.Entity.Biz;

namespace Rison.BusinessFacade.Facade.Biz
{
    public sealed class CPResultDetailFacade : FacadeBase
    {
        public CPResultDetailFacade() { }

        protected override DataAccessBase dbObject
        {
            get
            {
                if (dbHelper == null)
                    dbHelper = new CPResultDetailDb(GlobalParams.Instance.WSCPConnectionString);

                return dbHelper;
            }
        }

        protected override string identityFieldName
        {
            get { return "RDID"; }
        }


        protected override List<SqlField> GetSqlFieldCollection(object value, bool getIdentityField)
        {
            List<SqlField> fields = new List<SqlField>();
            if (getIdentityField)
                fields.Add(new SqlField("RDID", (value as CPResultDetail).RDID, true, false));
            fields.Add(new SqlField("WTSJ", (value as CPResultDetail).WTSJ, false));
            fields.Add(new SqlField("SJDW", (value as CPResultDetail).SJDW));
            fields.Add(new SqlField("SJRY", (value as CPResultDetail).SJRY));
            fields.Add(new SqlField("WTQK", (value as CPResultDetail).WTQK));
            fields.Add(new SqlField("SFJJ", (value as CPResultDetail).SFJJ, false));
            fields.Add(new SqlField("JYNR", (value as CPResultDetail).JYNR));
            fields.Add(new SqlField("XM", (value as CPResultDetail).XM));
            fields.Add(new SqlField("LXDH", (value as CPResultDetail).LXDH));
            fields.Add(new SqlField("Password", (value as CPResultDetail).Password));
            fields.Add(new SqlField("ResultId", (value as CPResultDetail).ResultId));

            return fields;
        }

        protected override object SetPropertiesValue(DataRow row)
        {
            CPResultDetail obj = new CPResultDetail();
            obj.RDID = Convert.ToInt64(row["RDID"]);
            obj.WTSJ = StringHelper.GetDateTimeValue(row, "WTSJ");
            obj.SJDW = StringHelper.GetValue(row, "SJDW");
            obj.WTQK = StringHelper.GetValue(row, "WTQK");
            obj.SFJJ = StringHelper.GetValue(row, "SFJJ");
            obj.SJRY = StringHelper.GetValue(row, "SJRY");
            obj.JYNR = StringHelper.GetValue(row, "JYNR");
            obj.XM = StringHelper.GetValue(row, "XM");
            obj.LXDH = StringHelper.GetValue(row, "LXDH");
            obj.Password = StringHelper.GetValue(row, "Password");
            obj.ResultId = StringHelper.GetValue(row, "ResultId");

            return obj;
        }

        public DataSet GetDepartments()
        {
            return GetDepartments(string.Empty);
        }

        public DataSet GetDepartments(string condition)
        {
            return (dbObject as CPResultDetailDb).GetDepartments(condition);
        }


        public bool PasswordExists(string password)
        {
            return (dbObject as CPResultDetailDb).PasswordExists(password);
        }

        public bool PasswordExistsNew(string password)
        {
            return (dbObject as CPResultDetailDb).PasswordExistsNew(password);
        }

        public DataSet GetWSCPbyPwd(string password)
        {
            return (dbObject as CPResultDetailDb).GetWSCPbyPwd(password);
        }

        public DataRow GetWSCPbydepart(string password, string departid)
        {
            return (dbObject as CPResultDetailDb).GetWSCPbydepart(password, departid);
        }

        #region "   保存测评结果   "
        public bool Save(List<WSCPResult> results, string userip, bool isPwdLogon)
        {
            lock (typeof(CPResultDetailFacade))
            {

                int reVal = 0; StringBuilder sql = null;

                try
                {
                    dbObject.BeginTransaction();

                    foreach (WSCPResult o in results)
                    {
                        string guid = Guid.NewGuid().ToString();

                        if (string.IsNullOrEmpty(o.RequestID))
                            o.RequestID = guid;

                        sql = new StringBuilder();
                        sql.Append("insert into EMail (ID,Sender,Phone,FromType) values ");
                        sql.AppendFormat("('{0}','{1}','{2}','{3}')", guid, (string.IsNullOrEmpty(o.XM) ? userip : o.XM), o.LXDH, (isPwdLogon) ? "密码登录" : "来信");

                        reVal = (dbObject as CPResultDetailDb).SaveResult(sql.ToString());

                        if (reVal > 0)
                        {
                            sql = new StringBuilder();
                            sql.Append("insert into EvaluationOnline (RequestID,YFXZ,XZXN,ZWGK,FWTD,QZLJ,GZCX,OccurrenceTime,UnitsInvolved,PeopleInvolved,IsVolved,Suggestion) values ");
                            sql.AppendFormat("('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", guid, o.YFXZ, o.XZXN, o.ZWGK, o.FWTD, o.QZLJ,o.GZCX, o.OccurrenceTime.ToString(), o.UnitsInvolved, o.PeopleInvolved, Convert.ToInt32(o.IsVolved).ToString(), o.Suggestion);

                            reVal = (dbObject as CPResultDetailDb).SaveResult(sql.ToString());
                        }

                        if (reVal > 0)
                        {
                            string categoryMailboxRelID = (dbObject as CPResultDetailDb).GetDepartmentCategoryRelId(o.BMGuid);
                            int sxh = (dbObject as CPResultDetailDb).GetSXH();

                            sql = new StringBuilder();
                            sql.AppendFormat("insert into Request (ID,MailBoxID,Type,RequestType,SendToType,SendToTag,SendToName,CategoryMailboxRelID,Title,Content,SubmitTime,Status,IsPublished,Password,BackNvarchar1,FromType,EvaluationUserPassword,EvaluationUserIP) values ");
                            sql.AppendFormat("('{0}','{1}','{2}','网上测评','{3}','{4}','{5}','{6}','{7}','{8}',getdate(),'UNOPERATE','0','111','{9}','{10}','{11}','{12}')", guid, o.BMGuid, o.Type, "部门", o.BMGuid, o.BMMC, categoryMailboxRelID, o.BMMC, o.WTQK, sxh.ToString("0000"),o.FromType,o.EvaluationUserPassword,o.EvaluationUserIP);

                            reVal = (dbObject as CPResultDetailDb).SaveResult(sql.ToString());
                        }
                    }

                    if (reVal > 0)
                        dbObject.CommitTransaction();
                    else
                        dbObject.RollBackTransaction();

                }
                catch
                {
                    reVal = -1; dbObject.RollBackTransaction();
                }
                finally
                {
                    sql = null;
                }

                return reVal > 0;
            }
        }
        #endregion


        #region "   保存测评结果(初始实现）   "
        public bool Save_original(List<CPResult> results, CPResultDetail detail, string userip)
        {
            lock (typeof(CPResultDetailFacade))
            {
                long reVal = 0; StringBuilder sql = null;
                try
                {
                    string groupid = Guid.NewGuid().ToString();

                    dbObject.BeginTransaction();

                    foreach (CPResult r in results)
                    {
                        sql = new StringBuilder();
                        sql.Append("insert into Biz_CPResult (CPND, BMGuid, CPXM, CPJG, TJSJ,CPRIP,GroupId) values ");
                        sql.AppendFormat("({0},'{1}','{2}','{3}',getdate(),'{4}','{5}')", r.CPND.ToString(), r.BMGuid, r.CPXM, r.CPJG, userip, groupid);

                        reVal = (dbObject as CPResultDetailDb).SaveResult(sql.ToString());

                        if (reVal < 0)
                            break;
                    }

                    if (reVal > 0 && detail != null)
                    {
                        detail.ResultId = groupid;

                        //bool success = false;
                        //while (success == false)//确保密码没有重复
                        //{
                        //    detail.Password = StringHelper.GetRadomString(GlobalParams.Instance.PasswordLength, false);

                        //    success = !(dbObject as CPResultDetailDb).PasswordExists(detail.Password);
                        //}

                        reVal = base.Save(detail);
                    }

                    if (reVal > 0)
                        dbObject.CommitTransaction();
                    else
                        dbObject.RollBackTransaction();
                }
                catch
                {
                    reVal = -1;
                    dbObject.RollBackTransaction();
                }
                finally
                {
                    sql = null;
                }

                return reVal > 0;
            }
        }
        #endregion




    }
}